// https://help.aliyun.com/document_detail/32067.html?spm=a2c4g.11186623.0.0.5bdb778f4JcP7T
const OSS = require('ali-oss')
const log = require('../log')
const packageJson = require('../package.json')

const UP = {}

// 检验必填配置项
UP.check = (options) => {
  log.yellow(`[${packageJson.name}] CDN >> Ali Cloud OSS ...`)
  let isError = false
  if (!options.accessKeyId) {
    isError = true
    log.red(`[${packageJson.name}] accessKeyId not found in options.oss`)
  }
  if (!options.accessKeySecret) {
    isError = true
    log.red(`[${packageJson.name}] accessKeySecret not found in options.oss`)
  }
  if (!options.bucket) {
    isError = true
    log.red(`[${packageJson.name}] bucket not found in options.oss`)
  }
  if (!options.region) {
    isError = true
    log.red(`[${packageJson.name}] region not found in options.oss`)
  }
  if (isError) {
    log.red('[Ali Cloud OSS] Related Documents: https://help.aliyun.com/document_detail/64097.html')
    return false
  }
  return true
}

/**
 * 上传
 * @param {String} uploadPath 上传路径
 * @param {String} localPath 本地文件路径
 * @param {Object} options 配置项请查看Ali Cloud OSS官方文档:https://help.aliyun.com/document_detail/64097.html
 */
UP.put = async(uploadPath, localPath, options) => {
  // 上传
  try {
    const result = await new OSS(options).put(uploadPath, localPath)
    log.green(`Upload Success => ${result.url}`)
    return null
  } catch (err) {
    log.red(`[${packageJson.name}] Upload Error => ${uploadPath}`)
    return err
  }
  return null
}

module.exports = UP
